package il.ac.tau.cg.ex5.rendering;

import il.ac.tau.cg.ex5.obj.ObjEntity;
import il.ac.tau.cg.ex5.util.Color;
import il.ac.tau.cg.ex5.util.Face;
import il.ac.tau.cg.ex5.util.Vertex;

import javax.media.opengl.GL2;

public class DisplayListsRenderer extends Renderer
{
	private static final String NAME = "Display lists";
	
	private int roomListIndex;
	private int objListIndex;
	
	private ObjEntity roomEntity;
	private ObjEntity objEntity;
	
	public DisplayListsRenderer(ObjEntity roomEntity, ObjEntity objEntity)
	{
		this.roomEntity = roomEntity;
		this.objEntity = objEntity;
	}
	
	@Override
	public String getName()
	{
		return NAME;
	}
	
	@Override
	public void init(GL2 gl)
	{
		super.init(gl);
		
		roomListIndex = initializeEntity(gl, roomEntity);
		objListIndex = initializeEntity(gl, objEntity);
	}
	
	@Override
	protected void renderRoom(GL2 gl)
	{
		gl.glCallList(roomListIndex);
	}
	
	@Override
	protected void renderObj(GL2 gl)
	{
		gl.glCallList(objListIndex);
	}
	
	private int initializeEntity(GL2 gl, ObjEntity objEntity)
	{
		int listIndex = gl.glGenLists(1);
		
		gl.glNewList(listIndex, GL2.GL_COMPILE);
		gl.glBegin(GL2.GL_QUADS);
		
		Face[] faces = objEntity.getFaces();
		
		for (int i = 0; i < faces.length; i++)
		{
			Face face = faces[i];
			
			Vertex v0 = face.vertices[0];
			Vertex v1 = face.vertices[1];
			Vertex v2 = face.vertices[2];
			Vertex v3 = face.vertices[3];
			
			Vertex n0 = face.normals[0];
			Vertex n1 = face.normals[1];
			Vertex n2 = face.normals[2];
			Vertex n3 = face.normals[3];
			
			Color c0 = face.colors[0];
			Color c1 = face.colors[1];
			Color c2 = face.colors[2];
			Color c3 = face.colors[3];
			
			gl.glColor3f(c0.r, c0.g, c0.b);
			gl.glNormal3f(n0.x, n0.y, n0.z);
			gl.glVertex3f(v0.x, v0.y, v0.z);
			
			gl.glColor3f(c1.r, c1.g, c1.b);
			gl.glNormal3f(n1.x, n1.y, n1.z);
			gl.glVertex3f(v1.x, v1.y, v1.z);
			
			gl.glColor3f(c2.r, c2.g, c2.b);
			gl.glNormal3f(n2.x, n2.y, n2.z);
			gl.glVertex3f(v2.x, v2.y, v2.z);
			
			gl.glColor3f(c3.r, c3.g, c3.b);
			gl.glNormal3f(n3.x, n3.y, n3.z);
			gl.glVertex3f(v3.x, v3.y, v3.z);
		}
		
		gl.glEnd();
		gl.glEndList();
		
		return listIndex;
	}
}
